import { Reducer, Effect, history } from 'umi';
import { apiLogin, Logincaptcha, apiEmiLogin } from '@/server/login';

export interface LoginState {
  data: {};
  logincaptchaCode: {};
  emiLogin: {};
}

export interface TagModelType {
  namespace: 'login';
  state: LoginState;
  effects: {
    fetchLogin: Effect;
    fetchLogincaptcha: Effect;
    fetchEmiLogin: Effect;
  };
  reducers: any;
}

const Login: TagModelType = {
  namespace: 'login',
  state: { data: {}, logincaptchaCode: {}, emiLogin: {} },
  effects: {
    *fetchLogin({ payload, callback }: any, { put, call }: any) {
      const data = yield call(apiLogin);
      yield put({
        type: 'setLoginState',
        payload: data,
      });
    },

    *fetchLogincaptcha({ payload }, { put, call }: any) {
      console.log(payload, 'payload');
      const data = yield call(Logincaptcha, payload);
      yield put({
        type: 'setLogincaptcha',
        payload: data,
      });
    },
    *fetchEmiLogin({ payload }, { put, call }: any) {
      const data = yield call(apiEmiLogin, payload);
      yield put({
        type: 'setEmiLogin',
        payload: data,
      });
    },
  },
  reducers: {
    setLoginState(state: LoginState, { payload }: any) {
      return { ...state, data: payload };
    },
    setLogincaptcha(state: LoginState, action: { payload: any }) {
      if (action.payload.data) {
        return { ...state, logincaptchaCode: action.payload };
      }
    },
    setEmiLogin(state: LoginState, action: { payload: any }) {
      sessionStorage.setItem(
        'user',
        JSON.stringify({
          account: action.payload.account,
          token: action.payload.token,
          loginType: action.payload.loginType,
          cookie: action.payload.cookie,
        }),
      );
      if (action.payload.code === 200) {
        history.goBack();
      }
    },
  },
};

export default Login;
